package main

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
)

const (
	ErrorLog = "err"
	WarnLog  = "warn"
	InfoLog  = "info"
	AllLog   = "log"
)

type FileLevelHook struct {
	files   map[string]*os.File
	logPath string
	appName string
}

func (h *FileLevelHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

func (h *FileLevelHook) Fire(entry *logrus.Entry) error {
	line, _ := entry.String()
	var level string

	switch entry.Level {
	case logrus.ErrorLevel:
		level = ErrorLog
	case logrus.WarnLevel:
		level = WarnLog
	case logrus.InfoLevel:
		level = InfoLog
	default:
		level = AllLog
	}
	h.createFile(level)
	_, err := h.files[level].Write([]byte(line))
	if level != AllLog {
		h.createFile(AllLog)
		_, err = h.files[AllLog].Write([]byte(line))
	}
	return err
}

func (h *FileLevelHook) createFile(level string) {
	f, ok := h.files[level]
	if ok && f != nil {
		return
	}
	_, err := os.Stat(h.logPath)
	err = os.MkdirAll(h.logPath, os.ModePerm)
	if err != nil {
		logrus.Errorln(err)
		return
	}
	h.files[level], err = os.OpenFile(fmt.Sprintf("%s/%s_%s.log", h.logPath, h.appName, level), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
	if err != nil {
		logrus.Errorln(err)
		return
	}
}

func InitFileLevelHook(logRootPath, appName string) {
	fileHook := FileLevelHook{files: make(map[string]*os.File), logPath: logRootPath, appName: appName}
	logrus.AddHook(&fileHook)
}
